package org.atfeihu.springcloud.alibaba.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.atfeihu.springcloud.alibaba.dao.OrderDao;
import org.atfeihu.springcloud.alibaba.domain.Order;
import org.atfeihu.springcloud.alibaba.service.AccountService;
import org.atfeihu.springcloud.alibaba.service.OrderService;
import org.atfeihu.springcloud.alibaba.service.StorageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wangfeihu
 * @create 2021/9/12 18:54
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        log.info("==================> 【订单微服务】新建订单(开始)......");

        // 创建订单
        orderDao.create(order);

        // 扣减库存
        log.info("==================> 【订单微服务】远程调用【库存微服务】, 扣减库存(开始)......");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("==================> 【订单微服务】远程调用【库存微服务】, 扣减库存(结束)......");

        // 扣减账户余额
        log.info("==================> 【订单微服务】远程调用【账户微服务】, 扣减账户余额(开始)......");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("==================> 【订单微服务】远程调用【账户微服务】, 扣减账户余额(结束)......");

        // 修改订单状态
        log.info("==================> 【订单微服务】修改订单状态(开始)......");
        orderDao.update(order.getUserId(), 0);
        log.info("==================> 【订单微服务】修改订单状态(结束)......");

        log.info("==================> 【订单微服务】新建订单(结束)......");
    }
}
